package com.dcits.servicemanagement.config.service;

import com.dcits.servicemanagement.entity.SysPermission;
import com.dcits.servicemanagement.entity.SysUser;
import com.dcits.servicemanagement.exception.NotLoginException;
import com.dcits.servicemanagement.service.SysPermissionService;
import com.dcits.servicemanagement.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;

import java.util.ArrayList;
import java.util.List;

/**
 * @Classname UserDetailsServiceImpl
 * @Description TODO
 * @Version 1.0.0
 * @Date 2022/4/22 16:19
 * @Created by hejle
 */
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysPermissionService sysPermissionService;

    @Override
    public UserDetails loadUserByUsername(String account) {

        if (null == account || "".equals(account)) {
            throw new NotLoginException("用户不能为空");
        }
        //根据用户名查询用户
        SysUser sysUser = sysUserService.selectByAccount(account);
        if(sysUser == null){
            throw new NotLoginException("用户不存在");
        }

        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        if (sysUser != null) {
            //获取该用户所拥有的权限
            //这里写死user_id，以后新增审批再放开
            sysUser.setId(1);
            List<SysPermission> sysPermissions = sysPermissionService.selectListByUser(sysUser.getId());
            // 声明用户授权
            sysPermissions.forEach(sysPermission -> {
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(sysPermission.getPermissionCode());
                grantedAuthorities.add(grantedAuthority);
            });
        }
        return new User(sysUser.getAccount(), sysUser.getPassword(), sysUser.getEnabled(),
                sysUser.getAccountNonExpired(), sysUser.getCredentialsNonExpired(), sysUser.getAccountNonLocked(), grantedAuthorities);

    }
}
